import * as echarts from 'echarts'
import type { ChartPropsInt, chartOptionsInt } from './charTypes'
import { getBaseColor } from './charBase'
/**
 *
 * @param echartsRef 图表Ref
 * @param props 图表基本入参
 * @param options 各类图表独有配置
 * @returns
 */
export function useChart(
  echartsRef: Ref<HTMLElement>,
  props: ChartPropsInt,
  options?: any,
  emits?: (event: 'chartClick', ...args: any[]) => void,
  dataChangeFn?: (newVal: any) => void
) {
  // const myChart = ref()
  let myChart: any

  const setOptionFn = () => {
    return {
      tooltip: {
        show: true,
        trigger: 'axis'
      },
      grid: props.grid,
      xAxis: {
        show: true,
        axisTick: false,
        axisLine: {
          lineStyle: {
            color: props.color ? props.color : getBaseColor()
          }
        },
        axisLabel: {
          color: '#000',
          interval: 0
        },
        type: 'category',
        data: props.xAxisData
      },
      yAxis: {
        show: true,
        type: 'value',
        axisLine: {
          show: true, // 显示轴线
          lineStyle: {
            color: getBaseColor()
          }
        },
        axisLabel: {
          color: '#000',
          formatter: function (value: number) {
            // 当值为0时，返回空字符串，不显示标签
            return value === 0 ? '' : value
          }
        },
        splitLine: {
          show: true,
          lineStyle: {
            type: 'solid',
            color: getBaseColor()
          }
        }
      },
      ...options
    }
  }
  const initChart = () => {
    if (myChart) {
      myChart.dispose()
      myChart.clear()
      myChart = ''
    }
    // 初始化 Echarts 实例
    myChart = echarts.init(echartsRef.value)
    const option: chartOptionsInt = setOptionFn()
    myChart.setOption(option)
    window.addEventListener('resize', function () {
      myChart.resize()
    })

    // 图标点击
    myChart.on('click', (params: any) => {
      emits && emits('chartClick', params)
    })
  }

  onMounted(() => {
    // 初始化
    initChart()
    // 定时更新数据-只做动画更新不做数据更新
    // setInterval(() => {
    // const optionBf = myChart.value.getOption()
    // myChart.value.clear() // 清空画布
    // myChart.value.dispose()
    // myChart.value.setOption(optionBf) // 重新绘制
    // }, 1000 * 10)
  })
  watch(
    () => props.chartData,
    (newVal, oldVal) => {
      dataChangeFn && dataChangeFn(newVal)
      initChart()
    },
    {
      deep: true
    }
  )
  return {
    initChart
  }
}
